package com.bw.controller;

import cn.hutool.core.util.StrUtil;
import com.bw.common.JwtUtils;
import com.bw.common.Md5Utils;
import com.bw.entity.User;
import com.bw.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.util.List;

@Controller
public class LoginController {

    @Autowired
    UserMapper userMapper;


    @RequestMapping("/loginPage.do")
    public String loginPage() {


        return "login";
    }

    /**
     * jsr303 验证
     *
     * @param loginUser
     * @param model
     * @param request
     * @return
     */
    @RequestMapping("/login.do")
    public String login(@Valid User loginUser, BindingResult result, Model model, HttpServletRequest request, HttpServletResponse response) {

        // 1.  非空
        if (result.hasErrors()) {
            String defaultMessage = result.getAllErrors().get(0).getDefaultMessage();

            model.addAttribute("error", defaultMessage);
            return "login";
        }


        User userFromDB = userMapper.selectByName(loginUser.getName());
        // 用户名不存在
        if (userFromDB == null) {
            model.addAttribute("error", "用户不存在");
            return "login";
        }

        //   密码错误

        String password = userFromDB.getPassword();// 数据库里的密码   202cb962ac59075b964b07152d234b70
        String loginPassword = loginUser.getPassword();// 用户输入的密码  123

        String salt = userFromDB.getSalt();// admin 这个用户的盐

        // 加密  用户输入的密码  和数据库里的盐
        String md5String = Md5Utils.getMD5String(loginPassword + salt);

        // 密码是否相等
        if (!md5String.equals(password)) {
            model.addAttribute("error", "密码错误");
            return "login";
        }
        // 加密用户信息 得到token
        String token = JwtUtils.createToken(userFromDB);

        // 把token放入cookie
        Cookie cookie = new Cookie("token", token);
        // 设置cookie 30min 过期之后 浏览器会自动删除保存的cookie
        cookie.setMaxAge(60 * 30);
        // 把cookie返回给浏览器
        response.addCookie(cookie);

        // 登录成功 重定向到列表页
        return "redirect:list.do";
    }

}
